package org

import (
	"time"
	"dhfshop/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

func init() {
	orm.RegisterModel(new(IdentCode))
}

//短消息生成验证码
type IdentCode struct {
	Id        int64     `orm:"auto;pk;column(id)" json:"id"`
	Mobile    int64     `orm:"column(mobile)" json:"mobile"`
	Code      int64     `orm:"column(code)" json:"code"`
	CreateAt  time.Time `orm:"auto_now_add;type(datetime);column(created_at)" json:"-"`
	ExpiresAt time.Time `orm:"column(expires_at)" json:"expiresAt"`
	Actived   bool      `orm:"column(actived)" json:"-"`
}

//创建验证码
func CreateIdentCode(identCode *IdentCode) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(identCode)
	return
}

//检测验证码的有效性
func CheckIdentCode(mobile, code string) bool {
	identCode := &IdentCode{Id: 0}
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(IdentCode))
	qs = qs.Filter("Mobile", mobile).Filter("Code", code).Filter("Actived", false).OrderBy("-id")
	qs.One(identCode)

	if identCode.Id > 0 {
		if time.Now().UTC().Before(identCode.ExpiresAt) {
			//验证码已被激活
			orm.NewOrm().QueryTable(new(IdentCode)).Filter("Mobile", mobile).Update(orm.Params{
				"Actived": true,
			})
			return true
		} else {
			beego.Info("过期")
			return false
		}

	} else {
		return false
	}

}
